<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">{{ isLogin ? '登录' : '注册' }}</h2>
      
      <van-form @submit="onSubmit">
        <van-field
          v-model="form.username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '请输入用户名' }]"
        />
        <van-field
          v-model="form.password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请输入密码' }]"
        />
        
        <div style="margin: 24px 16px;">
          <van-button round block type="primary" native-type="submit">
            {{ isLogin ? '登录' : '注册' }}
          </van-button>
        </div>
      </van-form>
      
      <div class="switch-mode">
        <span @click="switchMode">
          {{ isLogin ? '没有账号？去注册' : '已有账号？去登录' }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { Form, Field, Button, showSuccessToast, showFailToast } from 'vant'
import { userApi } from '@/api'
import config from '@/config'

const router = useRouter()
const isLogin = ref(true)
const form = ref({
  username: '',
  password: ''
})

function switchMode() {
  isLogin.value = !isLogin.value
  form.value = {
    username: '',
    password: ''
  }
}

async function onSubmit() {
  try {
    console.log(`使用环境: ${config.env}, 基础URL: ${config.baseUrl}`)
    
    let result
    if (isLogin.value) {
      result = await userApi.login(form.value)
    } else {
      result = await userApi.register(form.value)
    }
    
    // 保存令牌和用户信息到本地存储
    localStorage.setItem('token', result.token)
    localStorage.setItem('user', JSON.stringify(result.user))
    
    showSuccessToast(isLogin.value ? '登录成功' : '注册成功')
    router.push('/')
  } catch (error) {
    console.error('登录/注册失败:', error)
    const message = error.response?.data?.error || '服务器错误'
    showFailToast(message)
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  background: #f6f7fb;
  padding: 120px 20px 20px 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  padding: 24px 16px;
}

.login-title {
  text-align: center;
  margin-bottom: 24px;
  color: #333;
  font-size: 24px;
}

.switch-mode {
  text-align: center;
  margin-top: 16px;
  color: #27c19e;
  font-size: 14px;
}

.switch-mode span {
  cursor: pointer;
}
</style> 